package com.wan.controller;

import com.wan.entity.Order;
import com.wan.service.IOrderService;
import com.wan.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sf
 * @since 2025-01-15
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    public OrderController(IOrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("/list")
    public R<List<Order>> getOrders(@RequestParam(required = false) String status,
                                    @RequestParam(required = false) String userId) {
        List<Order> orders = orderService.getOrdersByStatusAndUserId(status, userId);
        return R.ok(orders);
    }

    @GetMapping("/detail/{orderId}")
    public R<Order> getOrderDetails(@PathVariable Long orderId) {
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return R.error("订单未找到");
        }
        return R.ok(order);
    }

    @PutMapping("/update/status/{orderId}")
    public R<String> updateOrderStatus(@PathVariable Long orderId, @RequestParam String status) {
        boolean isUpdated = orderService.updateOrderStatus(orderId, status);
        if (isUpdated) {
            return R.ok("订单状态更新成功");
        } else {
            return R.error("订单状态更新失败");
        }
    }

    @PutMapping("/assign/shipping/{orderId}")
    public R<String> assignShippingCode(@PathVariable Long orderId, @RequestParam String shippingCode) {
        boolean isAssigned = orderService.ShippingCode(orderId, shippingCode);
        if (isAssigned) {
            return R.ok("物流单号分配成功");
        } else {
            return R.error("物流单号分配失败");
        }
    }

    @DeleteMapping("/delete/{orderId}")
    public R<String> deleteOrder(@PathVariable Long orderId) {
        boolean isDeleted = orderService.deleteOrder(orderId);
        if (isDeleted) {
            return R.ok("订单删除成功");
        } else {
            return R.error("订单删除失败");
        }
    }

    @GetMapping("/export")
    public R<String> exportOrderData() {
        String filePath = orderService.exportOrderData();
        return R.ok("订单数据导出成功，文件路径：" + filePath);
    }

}
